﻿using LiteDB;
using Public.Tools;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ChoJu.GlobalInfo
{
    public class LiteDBClient
    {
        private static readonly object _obj = new object();
        private static LiteDBClient _instance;
        public static LiteDBClient Instance
        {
            get
            {
                if (_instance == null)
                    lock (_obj)
                        if (_instance == null)
                            _instance = new LiteDBClient();

                return _instance;
            }
        }

        private LiteDatabase _db;
        private ILiteCollection<BsonDocument> _collection;

        public LiteDBClient()
        {
            var dir = Path.Combine(AppContext.BaseDirectory, "Config");
            if(Directory.Exists(dir) == false)
                Directory.CreateDirectory(dir);

            var dbFile = Path.Combine(dir, "config.db");
            var connectionString = $"Filename={dbFile}; Log=0";  // 禁用日志
            _db = new LiteDatabase(dbFile);
            _collection = _db.GetCollection<BsonDocument>("keyvalue");
        }

        public bool Set<T>(string key, T t) where T : new()
        {
            var value = Tool.ObjectToJson(t);
            var bol = _collection.Upsert(new BsonDocument { ["_id"] = key, ["value"] = value });
            return bol;
        }

        public bool Set(string key, string value)
        {
            var bol = _collection.Upsert(new BsonDocument { ["_id"] = key, ["value"] = value });
            return bol;
        }

        public T Get<T>(string key) where T : new()  
        {
            var doc = _collection.FindById(key);
            var value = doc?["value"]?.AsString ?? string.Empty;

            if (string.IsNullOrWhiteSpace(value) == true)
                return new T();

            return Tool.JsonToObject<T>(value);
        }

        public string Get(string key)
        {
            var doc = _collection.FindById(key);
            var value = doc?["value"]?.AsString ?? string.Empty;
            return value;
        }
    }

    public static class ConfigType
    {
        public static string Global { get { return nameof(Global); } }

        public static string Weight { get { return nameof(Weight); } }
    }

}
